<?php

namespace plugin\admin\app\model;

use plugin\admin\app\model\Base;

/**
 * @property integer $id (主键)
 * @property integer $name 换物类型名称
 * @property integer $need_audit 是否需要审核
 */
class ExchangeCategory extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_exchange_categories';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public static function list()
    {
        $data = self::all()->toArray();

        $newData = [];

        foreach ($data as $key=>$value) {
            $newData[] = ['name' => $value['name'], 'value' => $value['id']];
        }

        return $newData;
    }

    public static function getTree()
    {
        $data = self::orderBy('sort')->get()->toArray();

        foreach ($data as $key=>$value) {
            $data[$key]['value'] = $value['id'];
        }

        return self::buildTree($data);
    }

    public static function buildTree($categories, $parent_id = 0) {
        $tree = array();

        foreach ($categories as $category) {
            if ($category['pid'] == $parent_id) {
                $children = self::buildTree($categories, $category['id']);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }

        return $tree;
    }
    
}
